package com.boot.security.server.controller;

import com.boot.security.server.annotation.LogAnnotation;
import com.boot.security.server.common.Result;
import com.boot.security.server.common.ResultBuilder;
import com.boot.security.server.dao.RoleDao;
import com.boot.security.server.dto.RoleDto;
import com.boot.security.server.model.Role;
import com.boot.security.server.model.domain.SysPermission;
import com.boot.security.server.model.domain.SysRole;
import com.boot.security.server.model.param.PermissionParam;
import com.boot.security.server.page.table.PageTableHandler;
import com.boot.security.server.page.table.PageTableHandler.CountHandler;
import com.boot.security.server.page.table.PageTableHandler.ListHandler;
import com.boot.security.server.page.table.PageTableRequest;
import com.boot.security.server.page.table.PageTableResponse;
import com.boot.security.server.service.RoleService;
import com.boot.security.server.utils.BeanHelper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色相关接口
 *
 * @author Ming
 */
@Api(tags = "角色")
@RestController
@RequestMapping("/roles")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleDao roleDao;



    @GetMapping("/getList")
    @ApiOperation(value = "角色列表")
    public Map<String, Object> getRoleList (@RequestParam(value = "limit",required = false) Integer limit,
                                             @RequestParam(value = "page",required = false) Integer page) {
        PageHelper.startPage(page,limit);
        List<SysRole>roles = roleService.getRoleList();
        PageInfo<SysRole> rolesPageInfo = new PageInfo<>(roles);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", rolesPageInfo.getTotal());
        map.put("data", rolesPageInfo.getList());
        System.out.println("map = " + map);
        return map;
    }
    @GetMapping("/getPurviewList")
    @ApiOperation(value = "角色权限列表")
    public Map<String, Object> getPurviewList (@RequestParam("id") Integer id,
                                               @RequestParam(value = "limit",required = false) Integer limit,
                                               @RequestParam(value = "page",required = false) Integer page) {
        // 查询用户拥有的权限
        List<SysPermission>purviewList = roleService.getPurviewList(id);

        List<PermissionParam>  params = BeanHelper.copyWithCollection(purviewList, PermissionParam.class);


        // 查询所有菜单权限
        PageHelper.startPage(page,limit);
        List<SysPermission>permissions = roleService.getAllPurview();

        List<PermissionParam> params1 = BeanHelper.copyWithCollection(permissions, PermissionParam.class);

        PageInfo<SysPermission> permissionPageInfo = new PageInfo<>(permissions);

       if (CollectionUtils.isNotEmpty(params)){
           for (PermissionParam permissionParam : params1) {

               if (params.contains(permissionParam)){
                   permissionParam.setStatus(1);
               }

           }
       }

        PageInfo<PermissionParam> permissionParamPageInfo = new PageInfo<>(params1);

        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", permissionPageInfo.getTotal());
        map.put("data", permissionParamPageInfo.getList());
        System.out.println("map = " + map);
        return map;
    }



    @LogAnnotation
    @PostMapping("/save")
    @ApiOperation(value = "录入角色")
    public Result addRole (@RequestBody SysRole param) {


        return roleService.addRole(param);

    }

    @LogAnnotation
    @PostMapping("/deleteRole")
    @ApiOperation(value = "删除角色")
    public Result delRole (@RequestBody SysRole role) {



        return roleService.delRole(role.getId());

    }

    @LogAnnotation
    @GetMapping("/coles")
    @ApiOperation(value = "关闭权限")
    public Result coles (@RequestParam("roleid") Integer roleid,
                         @RequestParam("pid") Integer pid,
                         @RequestParam("parentId")Integer parentId) {

        roleService.coles(roleid,pid,parentId);
        return ResultBuilder.success();

    }

    @LogAnnotation
    @GetMapping("/open")
    @ApiOperation(value = "启用权限")
    public Result open (@RequestParam("roleid") Integer roleid,@RequestParam("pid") Integer pid, @RequestParam("parentId")Integer parentId) {
        roleService.open(roleid,pid,parentId);
        return ResultBuilder.success();

    }








    @LogAnnotation
    @PostMapping
    @ApiOperation(value = "保存角色")
    @PreAuthorize("hasAuthority('sys:role:add')")
    public void saveRole(@RequestBody RoleDto roleDto) {
        roleService.saveRole(roleDto);
    }

    @GetMapping
    @ApiOperation(value = "角色列表")
    @PreAuthorize("hasAuthority('sys:role:query')")
    public PageTableResponse listRoles(PageTableRequest request) {
        return new PageTableHandler(new CountHandler() {

            @Override
            public int count(PageTableRequest request) {
                return roleDao.count(request.getParams());
            }
        }, new ListHandler() {

            @Override
            public List<Role> list(PageTableRequest request) {
                List<Role> list = roleDao.list(request.getParams(), request.getOffset(), request.getLimit());
                return list;
            }
        }).handle(request);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id获取角色")
    @PreAuthorize("hasAuthority('sys:role:query')")
    public Role get(@PathVariable Long id) {
        return roleDao.getById(id);
    }

    @GetMapping("/all")
    @ApiOperation(value = "所有角色")
    @PreAuthorize("hasAnyAuthority('sys:user:query','sys:role:query')")
    public List<Role> roles() {
        return roleDao.list(Maps.newHashMap(), null, null);
    }

    @GetMapping(params = "userId")
    @ApiOperation(value = "根据用户id获取拥有的角色")
    @PreAuthorize("hasAnyAuthority('sys:user:query','sys:role:query')")
    public List<Role> roles(Long userId) {
        return roleDao.listByUserId(userId);
    }

    @LogAnnotation
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除角色")
    @PreAuthorize("hasAuthority('sys:role:del')")
    public void delete(@PathVariable Long id) {
        roleService.deleteRole(id);
    }

}
